using System;
using System.Threading;

namespace Columbus
{
    /// <summary>
    /// Background class is used to queue operations to be executed in a background thread and dispatch exceptions to main thread
    /// </summary>
    public static class Background
    {
        static Background()
        {
            ResetToDefaults();
        }

        /// <summary>
        /// Executes action in background
        /// </summary>
        public static Action<Action> Execute;

        /// <summary>
        /// Resets class actions and functions back to their default implementations
        /// </summary>
        public static void ResetToDefaults()
        {
            ResetExecute();
        }

        private static void ResetExecute()
        {
            Execute = action => ThreadPool.QueueUserWorkItem(x =>
            {
                try
                {
                    action();
                }
                catch(Exception ex)
                {
                    Dispatcher.Dispatch(() => { throw new BackgroundException(ex); });
                }
            });
        }
    }
}